package yz.com.javautil.utilpackage;

import java.util.List;

/**
 * 比对字符串工具类（主要用于部分地址信息补全）
 *
 * @author yuanzheng
 */
public class CompareStrSimUtil {

    /**
     * 获取相似字符个数
     *
     * @param address 地址信息信息
     * @param zone    自治区、特别行政区信息
     * @return 比对成功的字数
     */
    public static int getSimilarityCount(String address, String zone) {
        return compare(address, zone);
    }


    /**
     * 比对两个字符串相似的字符个数（源字符串出现目标字符串字符的个数）
     *
     * @param sourceStr 源字符串
     * @param targetStr 目标字符串
     * @return 似的字符个数
     */
    private static int compare(String sourceStr, String targetStr) {

        int row = sourceStr.length();
        int column = targetStr.length();

        char rowChar;
        char columnChar;


        // 矩阵初始化
        int[][] matrix = new int[row + 1][column + 1];
        for (int i = 0; i <= row; i++) {
            matrix[i][0] = i;
        }
        for (int j = 0; j <= column; j++) {
            matrix[0][j] = j;
        }


        int temp;
        for (int rowIndex = 1; rowIndex <= row; rowIndex++) {
            rowChar = sourceStr.charAt(rowIndex - 1);
            for (int columnIndex = 1; columnIndex <= column; columnIndex++) {
                columnChar = targetStr.charAt(columnIndex - 1);
                if (rowChar == columnChar) {
                    temp = 0;
                } else {
                    temp = 1;
                }
                // 当前位置的上方、左侧、上左
                int min = min(matrix[rowIndex - 1][columnIndex] + 1, matrix[rowIndex][columnIndex - 1] + 1, matrix[rowIndex - 1][columnIndex - 1] + temp);
//                System.out.println("当前位置    " + rowIndex + ":" + columnIndex + "->[" + min + "]");
                matrix[rowIndex][columnIndex] = min;
            }
        }
//        for (int i = 0; i <= row; i++) {
//            for (int j = 0; j <= column; j++) {
//                System.out.print(matrix[i][j]);
//            }
//            System.out.println();
//        }
        return matrix[row][column];
    }

    private static int min(int one, int two, int three) {
        return (one = Math.min(one, two)) < three ? one : three;
    }

    public static float getSimilarityRatio(String str, String target) {
        float ret;
        int max = Math.max(str.length(), target.length());
        if (max == 0) {
            ret = 1;
        } else {
            ret = 1 - (float) compare(str, target) / max;
        }
        return ret;
    }


}
